package com.xcc.httpUtils.builder;

import com.xcc.httpUtils.callback.IUplodingCallback;
import com.xcc.httpUtils.request.PostFormRequest;
import com.xcc.httpUtils.request.RequestCall;

import java.io.File;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * 表单请求
 */
public class PostFormBuilder extends BaseHttpRequestBuilder<PostFormBuilder> {
    protected List<FileInput> files = new ArrayList<>();
    protected IUplodingCallback mIUplodingCallback;

    public PostFormBuilder(String url) {
        super(url);
    }

    /**
     * 设置上传监听
     * @param iUplodingCallback IUplodingCallback
     * @return 当前对象
     */
    public PostFormBuilder setIUplodingCallback(IUplodingCallback iUplodingCallback) {
        this.mIUplodingCallback = iUplodingCallback;
        return this;
    }

    @Override
    public RequestCall build() {
        //创建 RequestCall 对象
        return new PostFormRequest(url, tag, params, headers, null, files, mIUplodingCallback).build();
    }

    /**
     * 添加多个文件
     * @param key  key
     * @param files 文件 map 集合.<文件名, File 对象>
     * @return 当前对象
     */
    public PostFormBuilder files(String key, Map<String, File> files) {
        for (String filename : files.keySet()) {
            this.files.add(new FileInput(key, filename, files.get(filename)));
        }
        return this;
    }

    /**
     * 添加一个上传文件
     *
     * @param key 上传文件的 key
     * @param filename 文件名
     * @param file 需要上传的文件
     * @return 当前对象
     */
    public PostFormBuilder addFile(String key, String filename, File file) {
        files.add(new FileInput(key, filename, file));
        return this;
    }

    public static class FileInput {
        public String key;
        public String filename;
        public File file;

        public FileInput(String key, String filename, File file) {
            this.key = key;
            this.filename = filename;
            this.file = file;
        }

        @Override
        public String toString() {
            return "FileInput{" +
                    "key='" + key + '\'' +
                    ", filename='" + filename + '\'' +
                    ", file=" + file +
                    '}';
        }
    }

    /**
     * 添加所有参数
     * @param params 参数 map 集合 <key, value>
     * @return 当前对象
     */
    public PostFormBuilder params(Map<String, String> params) {
        this.params = params;
        return this;
    }

    /**
     * 添加单个参数
     * @param key key
     * @param val value
     * @return 当前对象
     */
    public PostFormBuilder addParams(String key, String val) {
        if (this.params == null) {
            params = new LinkedHashMap<>();
        }
        params.put(key, val);
        return this;
    }
}
